import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { List, CheckList, Dialog } from "antd-mobile";
import { CheckCircleFill, CheckCircleOutline } from "antd-mobile-icons";
import { TitleBlk } from "@components";
import { getTenantId, createAction } from "@common/utils";
import { getTenantList, getTenantInfo } from "@store/user-profile/selectors";
import { SAGA_USER_PROFILE_SWITCH_TENANT } from "@store/user-profile/saga-types";

const TenantInfo = () => {
  const dispatch = useDispatch();
  const token = useSelector((state) => state.globalState.token);
  const tenantList = useSelector((state) => getTenantList(state));
  const tenantInfo = useSelector((state) => getTenantInfo(state));
  const [currentTenant, setCurrentTenant] = useState([]);

  const updateCurrentTenant = () => {
    let currentTenantId = getTenantId(token);
    setCurrentTenant([currentTenantId]);
  };

  useEffect(() => {
    updateCurrentTenant();
  }, []);

  useEffect(() => {
    updateCurrentTenant();
  }, [token]);

  const handleChange = (vals) => {
    if (vals.length === 0) {
      return;
    }

    Dialog.confirm({
      content: "确定切换租户?",
      onConfirm: () => {
        dispatch(
          createAction(SAGA_USER_PROFILE_SWITCH_TENANT, { tenantId: vals[0] })
        );
      },
    });
  };

  return (
    <>
      <TitleBlk title="当前租户">
        <CheckList
          extra={(active) =>
            active ? <CheckCircleFill /> : <CheckCircleOutline />
          }
          value={currentTenant}
          onChange={handleChange}
        >
          {tenantList.map((record, idx) => (
            <CheckList.Item key={idx} value={record.id}>
              {record.name}
            </CheckList.Item>
          ))}
        </CheckList>
      </TitleBlk>
      <TitleBlk title="详细信息">
        <List>
          <List.Item title="名称">{tenantInfo.name}</List.Item>
          <List.Item title="形态">
            {tenantInfo.form === "REAL" ? "实体" : "虚拟"}
          </List.Item>
          <List.Item title="联系人">{tenantInfo.contacts}</List.Item>
          <List.Item title="办公地址">{tenantInfo.workAddress}</List.Item>
          <List.Item title="注册地址">{tenantInfo.regAddress}</List.Item>
          <List.Item title="备注">
            {tenantInfo.comments ? tenantInfo.comments : "--"}
          </List.Item>
        </List>
      </TitleBlk>
    </>
  );
};

export default TenantInfo;
